package br.com.galluzzo.operators;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

import br.com.galluzzo.modelo.Filtro;
import br.com.galluzzo.util.FilterParser;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;

@Path("filter")
public class FilterResource {
	@POST
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.TEXT_PLAIN)
	public String filtrar(@Context HttpHeaders ctx, String conteudo) {

		Filtro filtro = FilterParser.parseXML(conteudo);
		ByteArrayInputStream bais = new ByteArrayInputStream(filtro.getArquivo().getBytes());

		Model modeloOriginal = ModelFactory.createDefaultModel();
		Model modeloFiltrado = ModelFactory.createDefaultModel();
		System.out.println(filtro.getArquivo());
		modeloOriginal.read(bais,null);
		List<Statement> statements = new ArrayList<Statement>();

		String[] statement = filtro.getFiltros().split(",");
		Statement st = modeloFiltrado.createStatement(
				modeloFiltrado.createResource(statement[0].trim()),
				modeloFiltrado.createProperty(statement[1].trim()), statement[2].trim());
		statements.add(st);

		modeloOriginal = modeloOriginal.remove(statements);

		ByteArrayOutputStream os  = new ByteArrayOutputStream();
		modeloOriginal.write(os);
		String out = new  String(os.toByteArray());
		return out ;

	}
}
